﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AFT.Parking.WebSite.Common
{
    public class ZipResult:FileResult
    {
        private byte[] ZipContents { get; set; }
        public ZipResult(Stream stream, string contentType = "application/x-zip-compressed")
            : base(contentType)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            ZipContents = ToBytes(stream);
        }

        protected override void WriteFile(HttpResponseBase response)
        {
            const int buffSize = 1024*1024*100; //1M
            response.Clear();
            response.Buffer = true;
            response.AddHeader("Content-Type", "application/x-zip-compressed");
            response.AddHeader("Connection", "Keep-Alive");
            for (int i = 0; i < ZipContents.Length; i += buffSize)
            {
                var buffer = ZipContents.Skip(i).Take(buffSize).ToArray();
                response.BinaryWrite(buffer);
                response.Flush();
            }
            response.End();
        }

        private byte[] ToBytes(Stream stream)
        {
            var bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }
    }
}